package cn.edu.tsinghua.hpc.gsmtest.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class GSMDBAdapter {
	private static final String TAG = "TPositionDBAdapter";

	private static final String TABLE_GSM = "gsm";
	private static final String COLUMN_ROWID = "_id";
	private static final String COLUMN_LATITUDE_CID = "cid";
	private static final String COLUMN_LONGITUDE_LAC = "lac";
	private static final String COLUMN_LONGITUDE_LAT = "lat";
	private static final String COLUMN_LONGITUDE_LON = "lon";

	private static final int DATABASE_VERSION = 2;

	private static final String DATABASE_CREATE_GSM = "CREATE TABLE" + " "
			+ TABLE_GSM + " " + "(" + COLUMN_ROWID + " "
			+ "integer primary key autoincrement," + " " + COLUMN_LATITUDE_CID
			+ " " + "text," + " " + COLUMN_LONGITUDE_LAC + " " + "text," + " "
			+ COLUMN_LONGITUDE_LAT + " " + "text," + " " + COLUMN_LONGITUDE_LON
			+ " " + "text);";

	private final Context context;

	private DatabaseHelper DBHelper;

	private SQLiteDatabase db;

	public GSMDBAdapter(Context ctx) {

		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}

	public GSMDBAdapter open() throws SQLException {
		db = DBHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		DBHelper.close();
	}

	public Cursor getAllData() {
		return db.query(TABLE_GSM, new String[] { COLUMN_ROWID,
				COLUMN_LATITUDE_CID, COLUMN_LONGITUDE_LAC,
				COLUMN_LONGITUDE_LAT, COLUMN_LONGITUDE_LON }, null, null, null,
				null, null);
	}

	public int deleteAllData() {
		return db.delete(TABLE_GSM, null, null);
	}

	public int deleteOneData(long id) {
		return db.delete(TABLE_GSM, COLUMN_ROWID + "=" + id, null);
	}

	public long insertData(String lac, String cid, String lat, String lon) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(COLUMN_LATITUDE_CID, cid);
		initialValues.put(COLUMN_LONGITUDE_LAC, lac);
		initialValues.put(COLUMN_LONGITUDE_LAT, lat);
		initialValues.put(COLUMN_LONGITUDE_LON, lon);

		return db.insert(TABLE_GSM, null, initialValues);

	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, TABLE_GSM, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("DROP TABLE IF EXISTS gsm;");
			db.execSQL(DATABASE_CREATE_GSM);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS gsm");
			onCreate(db);

		}
	}
}
